package org.luxor.commons.security.config;

import org.luxor.commons.core.utils.PassWordUtils;
import org.luxor.commons.security.component.RestAccessDeniedHandler;
import org.luxor.commons.security.component.RestAuthExceptionEntryPoint;
import org.luxor.commons.security.constant.SecurityConstants;
import org.luxor.commons.security.utils.SecurityUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.Assert;

/**
 * 通用系统安全配置适配器
 *
 * @author Mr.Yan  @date: 2020/10/14
 */
public class DefaultWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

    private final WebSecurityProperties webSecurityProperties;

    public DefaultWebSecurityConfigurerAdapter(WebSecurityProperties webSecurityProperties) {
        Assert.notNull(webSecurityProperties, "Spring容器中找不到[webSecurityProperties]的实例化对象!");
        this.webSecurityProperties = webSecurityProperties;
    }

    /**
     * 配置鉴权机制
     *
     * @param http
     * @throws Exception
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {

        // 允许使用iframe 嵌套，避免swagger-ui 不被加载的问题
        http.headers().frameOptions().disable()
                .and().authorizeRequests()
                .antMatchers(SecurityConstants.DEFAULT_ANON_URIS).permitAll()
                .antMatchers(webSecurityProperties.getAnonUris()).permitAll()
                .anyRequest().authenticated()
                .and().anonymous().principal(SecurityUtils.ANONYMUS)
                .and().exceptionHandling()
                .authenticationEntryPoint(new RestAuthExceptionEntryPoint()).accessDeniedHandler(new RestAccessDeniedHandler())
                .and().csrf().disable();
    }


    @Override
    public void configure(WebSecurity web) {
        web.debug(webSecurityProperties.isDebugEnabled()).ignoring().antMatchers("/css/**");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return PassWordUtils.getInstance();
    }

}
